/**
 * 
 */
package com.cjlu.qiuyujia.jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.sun.jndi.url.ldaps.ldapsURLContextFactory;

/**
 * @author Administrator data access object == dao
 * 
 */
public class UserDao {
	// 插入用户 
	public void insert(User u) {
		String sql = "insert into user values(" + u.getUserid() + ",'"
				+ u.getUsername() + "','" + u.getPassword() + "')";

		JDBCConnection conn = new JDBCConnection();
		try {
			Connection connection = conn.getConection();
			Statement statement = connection.createStatement();
			statement.execute(sql);
			statement.close();
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 删除用户
	public void delete(User u) {
		String sql = "delete from user where id=0";

		JDBCConnection conn = new JDBCConnection();

		try {
			Connection connection = conn.getConection();
			Statement statement = connection.createStatement();
			statement.execute(sql);
			statement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// 按用户名查询用户
	public List<User> searchUser(String name) {
		String sql = "select * from t_user where user_name like '%" + name
				+ "%'";

		List<User> list = new ArrayList<User>();

		JDBCConnection conn = new JDBCConnection();

		try {
			Connection connection = conn.getConection();
			Statement statement = connection.createStatement();
			ResultSet result = statement.executeQuery(sql);
			while (result.next()) {
				User u = new User();
				u.setUserid(result.getInt(0));
				u.setUsername(result.getString(1));
				u.setPassword(result.getString(2));
				list.add(u);
			}
			statement.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}
}
